package com.llh.uua.filter

import com.llh.uua.util.JsonUtil
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 *
 * Created At 2021/3/20 16:47
 * @author llh
 */
class RestAuthenticationFilter : UsernamePasswordAuthenticationFilter() {

    override fun attemptAuthentication(
        request: HttpServletRequest,
        response: HttpServletResponse,
    ): Authentication {
        val authRequest = try {
            val stream = request.inputStream
            val jsonNode = JsonUtil.mapper.readTree(stream)
            val username = jsonNode.get("username").textValue()
            val password = jsonNode.get("password").textValue()
            UsernamePasswordAuthenticationToken(username, password)
        } catch (e: Exception) {
            throw BadCredentialsException("没有找到用户名或密码参数")
        }

        setDetails(request, authRequest)
        return this.authenticationManager.authenticate(authRequest)
    }
}